/**
 * Created by Administrator on 2017/5/10.
 */
var map = new BMap.Map("map");  // 创建Map实例
var point = new BMap.Point(118.10388605, 24.48923061);// 初始化地图,用城市名设置地图中心点
map.centerAndZoom(point, 15);//
map.enableScrollWheelZoom();//地图可以缩放

//声明两个对象用来缓存marker和peopleWindow，使用id来查询和添加缓存
var cacheMap = null;
var infoWindowMap = null;


/**
 * 自定义map
 * @constructor
 */
function Map() {

    var mapObj = {};

    this.put = function (key, value) {
        mapObj[key] = value;
    };

    this.remove = function (key) {
        if (mapObj.hasOwnProperty(key)) {
            delete mapObj[key];
        }
    };

    this.get = function (key) {
        if (mapObj.hasOwnProperty(key)) {
            return mapObj[key];
        }
        return null;
    };

    this.getKeys = function () {
        var keys = [];
        for (var k in mapObj) {
            keys.push(k);
        }
        return keys;
    };

    // 遍历map
    this.each = function (fn) {
        for (var key in mapObj) {
            fn(key, mapObj[key]);
        }
    };

    this.toString = function () {
        var str = "{";
        for (var k in mapObj) {
            str += "\"" + k + "\" : \"" + mapObj[k] + "\",";
        }
        str = str.substring(0, str.length - 1);
        str += "}";
        return str;
    }

}


/**查询地图上的全部人员**/

function queryPeople() {
    map.clearOverlays();
    $.ajax({
        type: "GET",
        url: "/rest/web/locationLog/selectAll",
        dataType: "json",
        data: {
            createTime: $("#createTime").val(),
            nickName: $("#nickName").val()
        },
        success: function (data) {
            //每次查询后都把marker和peopleWindow缓存的数据清空掉
            cacheMap = new Map();
            infoWindowMap = new Map();
            var peopleList = data.data;
            $.each(peopleList, function (i, o) {
                if (o.lng == null || o.lat == null) {
                    return;
                }
                setPeoplePoint(o);
            });
            var reportPeopleHtml = "";
            var statusTotal = 0;//声明的在线总数
            $.each(peopleList, function (i, n) {
                //查询在线的次数
                if (n.createTime !=null) {
                    statusTotal += 1;
                }
                var status = (n.createTime == null ? "离线" : "在线");
                if (i == 0) {
                    getSinglePeople(n.id);
                    reportPeopleHtml = reportPeopleHtml + "<li data-id='" + n.id + "'><p>" + (n.createTime == null ? "-" : n.createTime) + "</p> <p>" + status + "</p> <p>" + n.nickName + "</p></li>"
                }
                else {
                    reportPeopleHtml = reportPeopleHtml + "<li data-id='" + n.id + "'><p>" + (n.createTime == null ? "-" : n.createTime) + "</p> <p>" + status + "</p><p>" + n.nickName + "</p></li>"
                }
            });
            $("#reportPeople").html(reportPeopleHtml);
            $("#reportPeople>li").click(function () {
                getSinglePeople($(this).attr("data-id"));
            });
            //求出总数的方法
            var data = data.data;
            var dealWith = "";
            dealWith += "<div><p class='statusTotal'>在线：<span>" + statusTotal + "</span></p> <p>/总数：<span>" + data.length + "</span></p></div>";
            $(".dealWith-div").html(dealWith);
        }
    });
}
/**搜索框的模糊查询**/
$("#blurBtn").click(function () {
    queryPeople();
});

/**
 * 绘制点人员
 * @param obj
 */
function setPeoplePoint(obj) {
    var status = (obj.createTime == null ? "离线" : "在线");
    var peopleContent = "<div class='peopleContent  senseContent ' id='peopleDemo'>" +
        "<div><h5>" + obj.nickName + "&nbsp; </h5><p>" + obj.department + " &nbsp; &nbsp;  状态：<span>" + status + "</span></p></div>" +
        "<div><h6>当前位置：</h6><p>" + obj.address + "</p></div>" +
        "<div><h6>最近在线：</h6><p>" + obj.createTime + "</p></div>" +
        "<div><h6>手机号码：</h6><p>" + obj.phone + "</p></div>" +
        "<div><h6>坐标：</h6><p class='coordinate'>" + obj.lng + "," + obj.lat + "</p></div>" +
        "</div>";
    var opts = {
        width: 280,     // 信息窗口宽度
        height: 120,     // 信息窗口高度
    }
    var peopleWindow = new BMap.InfoWindow(peopleContent, opts); // 创建信息窗口对象
    //创建人员小图标
    var pt = new BMap.Point(obj.lng, obj.lat);
    var myIcon = new BMap.Icon("/static/images/map_people.png", new BMap.Size(22, 22));
    var marker = new BMap.Marker(pt, {icon: myIcon}); // 创建标注
    map.addOverlay(marker);
    marker.addEventListener("click", function () {
        this.openInfoWindow(peopleWindow);
        //图片加载完毕重绘infowindow
        document.getElementById('peopleDemo').onload = function () {
            peopleWindow.redraw(); //防止在网速较慢，图片未加载时，生成的信息框高度比图片的总高度小，导致图片部分被隐藏
        }
    });
    //将marker和peopleWindow缓存起来
    cacheMap.put(obj.id, marker);
    infoWindowMap.put(obj.id, peopleWindow);
}
/**
 * 根据id把缓存的marker和peopleWindow拼装后调用map的openInfoWindow方法弹窗展示
 * @param id
 */
function getSinglePeople(id) {
    var infoWindow = infoWindowMap.get(id);
    var marker = cacheMap.get(id);
    if (marker == null) {
        return;
    }
    marker.openInfoWindow(infoWindow);
}
var createTime = new Date(new Date()).Format("yyyy-MM-dd");
$("#createTime").val(createTime);
queryPeople();
/**查询地图上单个人员的轨迹**/
function queryTrajectory() {
    map.clearOverlays();
    $.ajax({
        type: "GET",
        url: "/rest/web/locationLog/selectAll",
        dataType: "json",
        data: {
            createTime: $("#createPathTime").val()
        },
        success: function (data) {
            var peopleList = data.data;
            var reportPeopleHtml = "";
            var statusTotal = 0;//声明的在线总数
            $.each(peopleList, function (i, n) {
                //查询在线的次数
                if (n.createTime !=null) {
                    statusTotal += 1;
                }
                var status = (n.createTime == null ? "离线" : "在线");
                if (i == 0) {
                    reportPeopleHtml = reportPeopleHtml + "<li data-id='" + n.createUser + "'><p>" + (n.createTime == null ? "-" : n.createTime) + "</p> <p>" + status + "</p> <p>" + n.nickName + "</p></li>"
                }
                else {
                    reportPeopleHtml = reportPeopleHtml + "<li data-id='" + n.createUser + "'><p>" + (n.createTime == null ? "-" : n.createTime) + "</p> <p>" + status + "</p><p>" + n.nickName + "</p></li>"
                }
            });
            $("#reportPathPeople").html(reportPeopleHtml);
            $("#reportPathPeople>li").click(function () {
                var createUser = $(this).attr("data-id");
                queryPath(createUser);
            });
            //求出总数的方法
            var data = data.data;
            var dealWith = "";
            dealWith += "<div><p class='statusTotal'>在线：<span>" + statusTotal + "</span></p><p>/总数：<span>" + data.length + "</span></p></div>";
            $(".dealPathWith-div").html(dealWith);
        }
    })
}
//绘制轨迹的线
function queryPath(createUser) {
    map.clearOverlays();
    $.ajax({
        type: "GET",
        url: "/rest/web/locationLog/selectLocationLog",
        dataType: "json",
        data: {
            createTime: $("#createPathTime").val(),
            createUser: createUser
        },
        success: function (data) {
            var pathList = data.data;
            for (var i = 0; i < pathList.length; i++) {
                drawPoint(pathList[i]);
                if (i < pathList.length - 1) {
                    drawLine(pathList[i], pathList[i + 1]);
                }
            }
        }
    })

}
function drawPoint(obj) {
    var objPt = new BMap.Point(obj.lng, obj.lat);
    var status = (obj.createTime == null ? "离线" : "在线");
    var peopleContent = "<div class='peopleContent  senseContent ' id='peopleDemo'>" +
        "<div><h5>" + obj.nickName + "&nbsp; </h5><p>" + obj.department + " &nbsp; &nbsp;  状态：<span>" + status + "</span></p></div>" +
        "<div><h6>当前位置：</h6><p>" + obj.address + "</p></div>" +
        "<div><h6>最近在线：</h6><p>" + obj.createTime + "</p></div>" +
        "<div><h6>手机号码：</h6><p>" + obj.phone + "</p></div>" +
        "<div><h6>坐标：</h6><p class='coordinate'>" + obj.lng + "," + obj.lat + "</p></div>" +
        "</div>";
    var opts = {
        width: 280,     // 信息窗口宽度
        height: 120,     // 信息窗口高度
    }
    var pipeWindow = new BMap.InfoWindow(peopleContent, opts); // 创建信息窗口对象
    var myIcon = new BMap.Icon("/static/images/map_people.png", new BMap.Size(22, 22));
    var marker = new BMap.Marker(objPt, {icon: myIcon}); // 创建标注
    map.centerAndZoom(objPt, 15);
    map.addOverlay(marker);
    marker.addEventListener("click", function () {
        this.openInfoWindow(pipeWindow);
    });
}
function drawLine(startObj, endObj) {
    var startPt = new BMap.Point(startObj.lng, startObj.lat);
    var endPt = new BMap.Point(endObj.lng, endObj.lat);
    var polyline = new BMap.Polyline([
        startPt,
        endPt
    ], {strokeColor: "blue", strokeWeight: 2});
    map.addOverlay(polyline);

}
var createTime = new Date(new Date()).Format("yyyy-MM-dd");
$("#createPathTime").val(createTime);
//点击轨迹清除地图点
queryTrajectory();
$("#path-page").click(function () {
    map.clearOverlays();
    queryTrajectory();
});
$("#message-page").click(function () {
    map.clearOverlays();
    queryPeople();
});



